﻿using BigFileUploadDemo4Framework.RRModels;
using System;
using System.IO;
using System.Linq;

namespace BigFileUploadDemo4Framework.Lib
{
    public class FileLib
    {
        
        /// <summary>
        /// 合并文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="md5">md5值</param>
        /// <param name="basepath">基础路径</param>
        /// <returns></returns>
        public UploadResponseModel MergeFileForWeb(string fileName, string md5, string basepath)
        {
            var UploadResponseModel = new UploadResponseModel();
            //临时文件夹
            var dir = Path.Combine(basepath, md5);
            //获得下面的所有文件
            var files = Directory.GetFiles(dir);
            var yearMonth = DateTime.Now.ToString("yyyyMM");
            //最终的文件名
            var finalDir = Path.Combine(basepath, yearMonth, md5);
            if (!Directory.Exists(finalDir))
                Directory.CreateDirectory(finalDir);
            var finalPath = Path.Combine(finalDir, fileName);

            using (var fs = new FileStream(finalPath, FileMode.Create))
            {
                //排一下序，保证从0-N Write
                var fileParts = files.OrderBy(x => x.Length).ThenBy(x => x);
                foreach (var part in fileParts)
                {
                    var bytes = System.IO.File.ReadAllBytes(part);
                    fs.Write(bytes, 0, bytes.Length);
                    bytes = null;
                    //删除分块
                    File.Delete(part);
                }
                fs.Flush();
                fs.Close();
                //删除临时文件夹和分片文件
                Directory.Delete(dir);
                UploadResponseModel.url = $"/upfile/{yearMonth}/{md5}/{fileName}";
                UploadResponseModel.uploadid = Guid.NewGuid().ToString("N");
            }
            return UploadResponseModel;
        }
    }
    
}